const {
	Backend,
	Joi
} = require('dx-router-admin');
const utils = require('../../utils.js')
const _ = require('underscore');
const fs = require('fs');
const path = require('path');
const reportObj =  uniCloud.importObject('report') //引入云对象实例

let progressData = {
	code:0,
	message:''
};
module.exports = class Menu extends Backend {
	constructor(ctx) {
		super(ctx);
		//this.multiFields = ['enable', 'is_link'];
		// this.dto = {
		// 	menu_id: Joi.string().required().error(new Error('菜单标识不能为空')),
		// 	name: Joi.string().required().error(new Error('菜单名称不能为空')),
		// 	enable: Joi.boolean().required().error(new Error('状态类型不正确')),
		// };
		
	}
	async del(param){
		await this.$dx.service.candidate.delByTid(param.ids);
		return super.del(param);
	}
	async index(param){
		let searchCompanyIds = [],searchCompanyList = [];
		if(param.company_name||param.company_ids){
			const clist = await this.$dx.service.company.findCompanyIds(param);
			const cids = _.pluck(clist,'_id');
			if(param.company_type==2){
				param['company_list._id'] = ['in',cids];
			}else{
				param['company_id'] = ['in',cids];
			}
			delete param.company_name;
			delete param.company_type;
			searchCompanyIds = cids;
			searchCompanyList = clist;
		}
		if(param._tid){
			param['company_list.teacher'] = ['contain',param._tid]
			delete param._tid;
		}
		//this.indexWith = ['company'];
		let t1 = new Date().getTime();
		const response = await super.index(param);
		//console.error('简历时间差：',t2 - t1)
		const list = response.data.list;
		const _ids = _.uniq(_.pluck(list,'company_id'));
		const companys = await this.$dx.service.company.findByIds(_ids);
		companys.push(...searchCompanyList);
		for(let i=0;i<list.length;i++){
			const company = _.findWhere(companys,{_id:list[i].company_id});
			if(company)list[i].company_name = company.name;
			const history = _.find(list[i].company_list,_history=>{
				if(searchCompanyIds.length){
					return searchCompanyIds.includes(_history._id); 
				}else{
					return list[i].company_id == _history._id
				}
			})
			if(history){
				const hcompany  = _.findWhere(companys,{_id:history._id});
				history.name = hcompany&&hcompany.name;
				history.timeGap = utils.timeGap(history.time);
				list[i].history = history;
			}
				//console.error(list[i].name,searchCompanyList);
			
		}
		//console.error(new Date().getTime() - t1,response.data)
		// this.indexWith =  [];
		let t2 = new Date().getTime();
		//console.error('时间差：',t2-t1);
		return response;
	}
	async findByIds(param){
		return await this.currentService.findByIds(param._ids);
	}
	async find(param){
		return await this.currentService.findWhere(param);
	}
	async resume(param){
		const talent =  await this.currentService.getResume(param);
		if(talent.avatar){
			if(talent.avatar.indexOf('//')==0){
				talent.avatar = 'http:'+ talent.avatar;
			}
			const {base64Img} = await utils.getImgBase64(talent.avatar);
			talent.avatarImg = base64Img
		}else{
			talent.avatarImg = '';
		}
		return talent;
	}
	//查找多个人物的基础信息
	async getTalents(param){
		return await this.currentService.getTalents(param);
	}
	async getTalentsByCompany(param){
		return await this.currentService.getTalentsByCompany(param);
	}
	getTalentsByTeacher(param){
		return this.currentService.getTalentsByTeacher(param);
	}
	getSearchTalents(param){
		return this.currentService.getSearchTalents(param);
	}
	resetSearchStatus(param){
		return this.currentService.resetSearchStatus(param);
	}
	async resumes(param){
		return  await this.currentService.getResumes(param);
		
	}
	async merge(param){
		/*************** 保存合并前的 id****************************/
		const merge_list = await this.currentService.where({_id:['in',param._ids]}).field('merge_ids').select();
		const merge_ids = [];
		_.each(merge_list,company=>{
			if(Array.isArray(company.merge_ids)){
				merge_ids.push(...company.merge_ids);
			}
		})
		merge_ids.push(...param._ids);
		/***********************************************/
		const result = await super.del({ids:param._ids});
		if(result.code==1000){
			const result2 = await super.add({...param.merge,merge_ids});
			await this.updateTMerge({_id:result2.data,_ids:param._ids})
			return result2;
		}else{
			return result
		}
	}
	async updateTMerge(param){
		//console.error('执行简历相关合并：',param,this.$dx.service.company.updateTMerge,666)
		await this.currentService.updateTMerge(param);        // 更新简历
		await this.$dx.service.candidate.updateTMerge(param);  //更新项目候选人
		//await this.$dx.service.company.updateTMerge(param);//  更新 公司 HR
		await this.$dx.service.job.updateTMerge(param);//  更新 职位 hr
		await this.$dx.service.project.updateTMerge(param);//  更新项目职位 hr
		return true;
	}
	async patent(param){
		// this.writeFile({
		// 	code:1,
		// 	message:'正在处理专利数据···'
		// })
		let users = _.keys(param);
		let companys = [];
		_.each(users,user=>{
			const company = _.keys(param[user]);
			companys.push(...company);
		})
		companys = _.uniq(companys);
		
		/*************创建公司操作******************/
		const clist = await this.$dx.service.company.findByNames(companys);
		companys = _.without(companys,..._.pluck(clist,'name')).map(name=>{
			return {name,from:'patent'}
		}); //去除已经存在的公司
		if(companys&&companys.length){
			const _cids = await this.$dx.service.company.insertAll(companys);
			companys = _.map(companys,(company,idx)=>{
				company._id = _cids[idx];
				return company;
			});
		}
		companys.push(...clist);//得到所有数据库带_id 的 公司
		/***#########暂不做查重操作#################**/
		users = users.map(name=>{
			return {
				name,
				from:'patent'
			}
		});
		/**********************************************/
		//from:'patent',
		const where = {name:['in',_.pluck(users,'name')],'company_list._id':['in',_.pluck(companys,'_id')]}
		const limitCount = 1000;
		const ulist = [];
		let count = limitCount;
		while(count==limitCount){
			const skip = ulist.length;
			const list = await this.currentService.where(where).field('name,job,company_list,company_id').skip(skip).limit(limitCount).select();
		    count = list.length;
			ulist.push(...list);
			//console.error(' 本次查询：',list.length,list);
		}
		// console.error('查询结果：',ulist.length,count)
		// return false;
		const uObj ={};
		ulist.forEach(user=>{
			uObj[user.name] = {
				_id:user._id,
				name:user.name,
				company_ids:_.pluck(user.company_list,'_id')
			}
		})
		/**********************************************************/
		for(let i = 0;i<users.length;i++){
			const user = users[i];
			const uObj = _.findWhere(ulist,{name:user.name});
			if(!uObj)continue;
			const ids1 = _.pluck(uObj.company_list||[],'_id');  //当前工作过的公司_id列表
			if(_.isEmpty(ids1))continue;
			/**********/
			const ids2 = Object.keys(param[user.name]).map(name=>{//公司名称
				const company = _.findWhere(companys,{name});
				return company&&company._id;
			})
			if(_.intersection(ids1,ids2).length>0){
				user._id = uObj._id;
				user.company_list = uObj.company_list;
				user.company_id = uObj.company_id;
				user.job = uObj.job;
				user.type = 'update';
			}
		}
		/***************************************************/
		const iuser = _.filter(users,user=>!user._id);
		
		if(iuser.length){
			const _uids = await this.currentService.insertAll(iuser);
			_.each(iuser,(uObj,idx)=>{
				const user = _.findWhere(users,{name:uObj.name});
				user&&(user._id = _uids[idx]);
			})
		}
		//console.error('新插入数据：',users);
		//return users;
		/***********************************************/
		const userList = [];
		const length = users.length;
		for(let i=0;i<length;i++){
			const user = users[i];
			const udata = {
				company_list:[],
				...user,
			};
			if(!udata.job){
				udata.job = 0;
			}else if(/^\d+$/.test(udata.job)){//如果是纯数字转化Number
				udata.job = parseInt(udata.job)
			} 
			//console.error('初始专利人：',JSON.stringify(udata));
			let company_id,endDate=0;
			_.keys(param[user.name]).forEach(name=>{ //公司名称列表
				const patent = param[user.name][name];//专利数据
				const company = _.findWhere(companys,{name}); // 公司数据
				const company_data = _.findWhere(udata.company_list,{_id:company._id})||{};  //要编辑的公司信息
			    /*************************************/
				if(!_.isEmpty(company_data)){
			    	const work = company_data.work||'';
			    	patent.work = _.filter(patent.work,wk=>{
			    		if(work.includes(wk)){
			    			patent.count--;
			    			return false;
			    		}
			    		return true;
			    	})
			    	if(patent.startDate&&company_data.time){
			    		const time1 = new Date(patent.startDate).getTime();
			    		const time2 = company_data.time[0]||0;
			    		if(time2<time1){
			    			patent.startDate = time2;
			    		}
			    	}
			    	if(patent.endDate&&company_data.time){
			    		const time1 = new Date(patent.endDate).getTime();
			    		const time2 = company_data.time[1]||0;
			    		if(time2>time1){
			    			patent.endDate = time2;
			    		}
			    	}
			    }
				let work = company_data.work||'';
				patent.work.forEach((text,idx)=>{
					const start = company_data.count||0;
					work+=`${start+idx+1}、${text}\n`
				})
				/*********************************/
				const time = [];
				if(patent.startDate){
					time[0] = new Date(patent.startDate).getTime();
				}
				if(patent.endDate){
					time[1] = new Date(patent.endDate).getTime();
				}
				if(time[1]&&time[1]>endDate&&!user.company_id){
					endDate = time[1];
					company_id = company._id;
				}
				let relations = (patent.relations||[]).map(name=>{
					const ruser = _.findWhere(users,{name});
					return ruser&&ruser._id;
				});
				relations = _.uniq([...relations,...company_data.relations||[]]);
				company_id&&(udata.company_id = company_id);
				/*******************************/
				if(_.isNumber(udata.job)&&patent.count>0){
					udata.job += parseInt(patent.count);
				}
				if(!_.isEmpty(company_data)){
					company_data.relations = relations;
					company_data.work = work;
					company_data.time = time;
				}else{
					udata.company_list.push({
						_id:company._id,
						type:'patent',
						relations,
						work,
						time
					})
				}
			})   
			delete udata.type;
			userList.push(udata)
			//const res = await this.currentService.update(udata);
			// await this.writeFile({
			// 	code:1,
			// 	message:`正在处理专利数据：总计：${length }条,当前：第${i} 条!`
			// })
			// console.error(udata.job,`正在处理专利数据：当前：第 ${i} 条总计：${length }条!`);
			// if(i>100){
			// 	this.writeFile({
			// 		code:2,
			// 		message:'专利处理完成'
			// 	})
			// 	return udata;
			// }
		}
		//return userList;
		// await this.writeFile({
		// 	code:2,
		// 	message:'正在处理专利数据'
		// })
		
		await this.batchUpdateTalent(userList,135)
		/************************************/
		await this.$dx.service.company.where('_id','in',_.pluck(companys,'_id')).update({
			has_patent:'1',
			patent_date:Date.now()
		});
		return {
			names:_.pluck(users,'name'),
			companys
		};
	}
	async batchUpdateTalent(list,count=100){
		const talents = list.slice(0,count);
		//await this.dealBatch(talents);
		// for(let i = 0;i<talents.length;i++){
		// 	await this.currentService.update(talents[i]);
		// }
		await this.batchUpload(talents);
		const other = list.slice(count);
		//console.error('剩余：',other.length);
		if(other.length){
			return await this.batchUpdateTalent(other);
		}else{
			return true;
		}
	}
	batchUpload(talents){
		const promiseList = [];
		for(let i=0;i<talents.length;i++){
			const _id = talents[i]._id;
			delete talents[i]._id;
			const res = this.currentService.where({_id}).update(talents[i]);
			promiseList.push(res);
		}
		
		return Promise.all(promiseList);
	}
	progress(){
		const filePath = path.join(__dirname, 'progress.json');
		const data = fs.readFileSync(filePath, 'utf8');
		return JSON.parse(data);
	}
	writeFile(data){
		const filePath = path.join(__dirname, 'progress.json');
		return new Promise((resolve)=>{
			fs.writeFileSync(filePath,JSON.stringify(data),'utf8');
			resolve();
		})
	}
	async doctor(param){
		const list = _.values(param);
		let companys = [];
		let teachers = [];
		_.each(list,user=>{
			companys.push(user.school);
			user.teacher.forEach(name=>{
				const tObj = _.findWhere(teachers,{name,school:user.school});
				if(!tObj){
					teachers.push({name,school:user.school});
				}
			})
		})
		companys = _.uniq(companys);
		/*************创建公司操作******************/
		const clist = await this.$dx.service.company.findByNames(companys);
		companys = _.without(companys,..._.pluck(clist,'name')).map(name=>{
			return {name,from:'doctor'}
		}); //去除已经存在的公司
		if(companys&&companys.length){
			const _cids = await this.$dx.service.company.insertAll(companys);
			companys = _.map(companys,(company,idx)=>{
				company._id = _cids[idx];
				return company;
			});
		}
		companys.push(...clist);//得到所有数据库带_id 的 公司
		/*****************教师操作******************************/
		const tnames = _.uniq(_.pluck(teachers,'name'));
		const tlist = await this.$dx.service.teacher.findByNames(tnames);
		let iteacher = [],oteacher = [];
		teachers.forEach(teacher=>{
			const tObj = _.findWhere(tlist,{name:teacher.name,school:teacher.school});
			if(tObj){
				teacher._id = tObj._id;
				oteacher.push(teacher)
			}else{
				iteacher.push(teacher);
			}
		})
		
		if(iteacher.length){
			const _tids = await this.$dx.service.teacher.insertAll(iteacher);
			iteacher = _.map(iteacher,(teacher,idx)=>{
				teacher._id = _tids[idx];
				return teacher;
			});
		}
		teachers = [...iteacher,...oteacher];
		
		/***#########暂不做查重操作#################**/
		const users = list.map(user=>{
			const company = _.findWhere(companys,{name:user.school});
			return {
				company_id:company&&company._id,
				name:user.name,
				from:'doctor'
			}
		});
		const where = {from:'doctor',name:['in',_.pluck(users,'name')],'company_list._id':['in',_.pluck(companys,'_id')]}
		const limitCount = 1000;
		const ulist = [];
		let count = limitCount;
		while(count==limitCount){
			const skip = ulist.length;
			const list = await this.currentService.where(where).field('name,job,company_list,company_id').skip(skip).limit(limitCount).select();
			count = list.length;
			ulist.push(...list);
		}
		/**********************************************************/
		const iuser = [];
		_.each(users,user=>{
			const uObj = _.findWhere(ulist,{name:user.name});
			if(!uObj){
				iuser.push(user)
			}else{
				user._id = uObj._id;
			}
		});
		if(!_.isEmpty(iuser)){
			const _uids = await this.currentService.insertAll(iuser);
			_.each(iuser,(uObj,idx)=>{
				const user = _.findWhere(users,{name:uObj.name});
				user&&(user._id = _uids[idx]);
				user&&(user.company_id = uObj.company_id);
			})
		}
		/**********************************************************/
		for(let i = 0;i<users.length;i++){
			const user = users[i];
			const uObj = _.findWhere(ulist,{name:user.name});
			const time = new Date(list[i].year).getTime();
			const mates = list[i].sames.map(name=>{
				const temp = _.findWhere(users,{name});
				return temp&&temp._id;
			})
			//console.log(111222,mates,list[i].sames)
			const company_id = _.findWhere(companys,{name:list[i].school})._id;
			/******************************************************************/
			const teacher = list[i].teacher.map(name=>{
				const tObj = _.findWhere(teachers,{name:name,school:list[i].school});
				return tObj&&tObj._id;
			})
			const company = {
				_id:company_id,
				work:list[i].product,
				type:'doctor',
				mates:mates,
				teacher:teacher,
				time:[time,time],
			}
			if(!uObj||_.isEmpty(uObj.company_list)){
				user.company_list = [company];
				continue;
			};
			const cObj = _.findWhere(uObj.company_list||[],{_id:company._id});
			if(cObj){
				/************************/
				cObj.mates = [...cObj.mates,...(company.mates||[])];
				cObj.teacher = [...cObj.teacher,...(company.teacher||[])];
				/***************************/
				Object.assign(cObj,company,cObj);
			}else{
				uObj.company_list.push(company);
			}
			Object.assign(user,uObj);
			
		}
		/************* 将 userList 插入数据表**************************/
		// for(let i = 0;i<users.length;i++){
		// 	const res = await this.currentService.update(users[i]);
		// 	res&&result.push(users[i]._id);
		// }
		await this.batchUpdateTalent(users)
		return _.pluck(users,'_id');
	}
	async update(param){
		const list = param.data;
		if(_.isEmpty(list)||!_.isArray(list)){
			return this.$dx.fail('参数错误')
		}
		for(let i=0;i<list.length;i++){
			await this.currentService.update(list[i]);
		}
		return this.$dx.success('更新成功')
	}
	/*下载候选人简历报告
	*/
	async download(param){
		const talent = await this.resume({_id:param.talent_id});
		if(talent.avatar){
			const {base64Img} = await utils.getImgBase64(talent.avatar);
			talent.avatarImg = base64Img
		}
		//const result = await reportObj.getDoc({...param,...talent})
		return {...param,...talent};
		//return this.$dx.success('更新成功',{...param,...talent})
	}
};